#include <windows.h>
#include <shellapi.h>
#include <tchar.h>
#include "dllmain.h"
#include "trayicon.h"
#include "resource.h"
#include "log.h"

NOTIFYICONDATA trayIcon;

HICON hIconNormal=NULL;
HICON hIconAlert=NULL;
HICON hIconError=NULL;


BOOL notifyTrayIcon(HWND hWnd, DWORD dwMsg, HICON hIcon, _TCHAR * szTip ) {
	trayIcon.cbSize           = sizeof(NOTIFYICONDATA);
	trayIcon.hWnd             = hWnd;
	trayIcon.uID              = 1;
	trayIcon.uFlags           = NIF_MESSAGE;// | NIF_ICON | NIF_TIP;
	trayIcon.uCallbackMessage = TIM_NOTIFY;
	if (hIcon) {
		trayIcon.uFlags      |= NIF_ICON;
		trayIcon.hIcon        = hIcon;
	}
	if (szTip) {
		trayIcon.uFlags      |= NIF_TIP;
		_tcsncpy(trayIcon.szTip, szTip, 64 );
	}
	if ( !Shell_NotifyIcon(dwMsg, &trayIcon) ) {
		log(_T("ERROR: notifyIcon:Shell_NotifyIcon failed.\n"));
		return false;
	}
	return true;
}


BOOL createTrayIcon(HWND hwnd) {
	_TCHAR tip[64];
	SendMessage(hwnd,WM_GETTEXT, 64, (LPARAM)tip);
	if (!hIconNormal) hIconNormal = (HICON)LoadImage(getInstance(),   MAKEINTRESOURCE(ICON_LOG), IMAGE_ICON, 16, 16, 0);
	if (!hIconAlert) hIconAlert = (HICON)LoadImage(getInstance(), MAKEINTRESOURCE(ICON_LOGINFO), IMAGE_ICON, 16, 16, 0);
	if (!hIconError) hIconError = (HICON)LoadImage(getInstance(), MAKEINTRESOURCE(ICON_LOGERR ), IMAGE_ICON, 16, 16, 0);
	return notifyTrayIcon(hwnd, NIM_ADD, hIconNormal, tip);
}

BOOL deleteTrayIcon(HWND hwnd) {
	return notifyTrayIcon(hwnd, NIM_DELETE);
}

BOOL alertTrayIcon(HWND hwnd,BOOL alert) {
	switch(alert){
		case 0:  //IconNormal
			if(trayIcon.hIcon==hIconNormal)return true;
			return notifyTrayIcon(hwnd, NIM_MODIFY, hIconNormal );
		case 1:  //IconAlert
			if(trayIcon.hIcon==hIconNormal)
				return notifyTrayIcon(hwnd, NIM_MODIFY, hIconAlert );
			return true;
		case 2:  //IconError
			if(trayIcon.hIcon==hIconError)return true;
			return notifyTrayIcon(hwnd, NIM_MODIFY, hIconError );
	}
	return notifyTrayIcon(hwnd, NIM_MODIFY, ( alert?hIconAlert:hIconNormal ) );
}

